package cn.stylefeng.guns.modular.gridsystem.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.stylefeng.guns.core.exception.ServiceException;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.modular.gridsystem.constants.GatewayTaskTypeConstant;
import cn.stylefeng.guns.modular.gridsystem.entity.BizGateway;
import cn.stylefeng.guns.modular.gridsystem.entity.CollectionModel;
import cn.stylefeng.guns.modular.gridsystem.enums.CollectionModelExceptionEnum;
import cn.stylefeng.guns.modular.gridsystem.mapper.BizGatewayMapper;
import cn.stylefeng.guns.modular.gridsystem.mapper.CollectionModelMapper;
import cn.stylefeng.guns.modular.gridsystem.model.param.CollectionModelParam;
import cn.stylefeng.guns.modular.gridsystem.model.result.CollectionModelResult;
import cn.stylefeng.guns.modular.gridsystem.service.CollectionModelService;
import cn.stylefeng.guns.modular.gridsystem.service.GatewayTaskService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * biz_collection_model 服务实现类
 *
 * @author zxw
 * @date 2022/11/01 15:32
 */
@Slf4j
@Service
public class CollectionModelServiceImpl extends ServiceImpl<CollectionModelMapper, CollectionModel> implements CollectionModelService {

    @Resource
    private GatewayTaskService taskService;
    @Resource
    private BizGatewayMapper gatewayMapper;

    /**
     * 分页查询biz_collection_model
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<CollectionModelResult> page(CollectionModelParam param) {
        return new PageResult<>(this.baseMapper.pagelist(PageFactory.defaultPage(), param));
    }

    /**
     * 添加biz_collection_model
     *
     * @param collectionModelParam
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(CollectionModelParam collectionModelParam) {
        // 将dto转为实体
        CollectionModel collectionModel = CollectionModel.builder().build();
        BeanUtil.copyProperties(collectionModelParam, collectionModel);
        this.save(collectionModel);
    }

    /**
     * 添加biz_collection_model
     *
     * @param model
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(CollectionModel model) {
        this.save(model);
    }

    /**
     * 删除biz_collection_model
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(CollectionModelParam param) {
        CollectionModel collectionModel = this.getById(param.getId());
        BizGateway gateway = gatewayMapper.selectById(collectionModel.getGatewayId());
        Map<String, Object> map = new HashMap<>();
        map.put("gatewayCode", gateway.getGatewayCode());
        map.put("expectAccessToken(", collectionModel.getExpectAccessToken());
        map.put("expectGroupId", collectionModel.getExpectGroupId());
        List<Integer> gatewayIds = new ArrayList<>();
        gatewayIds.add(gateway.getId());
        // 下发删除模型任务
        taskService.add(GatewayTaskTypeConstant.DELETE_MODEL, gateway.getId(), JSONUtil.toJsonStr(map));
        log.info(">>>  向采集端下发删除模型任务，网关主键为：{}", gateway.getId());
        this.queryCollectionModel(param);
        this.removeById(param.getId());

    }

    /**
     * 编辑biz_collection_model
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(CollectionModelParam param) {
        // 根据id查询实体
        CollectionModel collectionModel = this.queryCollectionModel(param);
        // 请求参数转化为实体
        BeanUtil.copyProperties(param, collectionModel);
        this.updateById(collectionModel);
    }

    /**
     * 同步模型
     *
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long sync(CollectionModelParam param) {
        // 在同步网关时再进行数据处理，此处不用删除数据
        this.remove(new LambdaQueryWrapper<CollectionModel>().eq(CollectionModel::getGatewayId, param.getGatewayId()));
        List<Integer> gatewayIds = new ArrayList<>();
        gatewayIds.add(param.getGatewayId());
        return taskService.add(GatewayTaskTypeConstant.SYNC_MODEL, param.getGatewayId(), null);
    }

    /**
     * 查看详情biz_collection_model
     *
     * @param collectionModelParam
     * @return
     */
    @Override
    public CollectionModel detail(CollectionModelParam collectionModelParam) {
        return this.queryCollectionModel(collectionModelParam);
    }


    /**
     * 获取biz_collection_model
     *
     * @author zxw
     * @since 2022/11/01 15:32
     */
    private CollectionModel queryCollectionModel(CollectionModelParam param) {
        CollectionModel collectionModel = this.getById(param.getId());
        if (ObjectUtil.isEmpty(collectionModel)) {
            log.warn("采集端模型不存在,模型主键为：{}", param.getId());
            throw new ServiceException(CollectionModelExceptionEnum.NOT_EXISTED);
        }
        return collectionModel;
    }
}
